package main

import (
	rr "fgo/advance/http/proxy/roundrobin"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

var RR = rr.NewWeightedRR(rr.RR_NGINX)

type handle struct {
	addrs []string
}

// ref: https://lihaoquan.me/2018/4/24/go-reverse-proxy.html
func (h *handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	addr := RR.Next().(string)
	remote, err := url.Parse("http://" + addr)
	if err != nil {
		panic(err)
	}
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, r)
}

// go run server.go --port 3001
// go run server.go --port 3000

func main() {
	//被代理的服务器host和port
	h := &handle{}
	h.addrs = []string{"localhost:3001", "localhost:3002"}

	w := 1
	for _, e := range h.addrs {
		RR.Add(e, w)
		w++
	}
	err := http.ListenAndServe(":9090", h)
	if err != nil {
		log.Fatalln("ListenAndServe: ", err)
	}
}
